package com.eqdd.yiqidian.ui.mine.shenqing;

import android.content.Intent;
import android.databinding.DataBindingUtil;

import com.bigkoo.pickerview.TimePickerView;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport;
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx;
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector;
import com.eqdd.yiqidian.adapter.slimadapter.viewinjector.IViewInjector;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.SickLeaveListActivityCustom;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.rebuild.ClockBean;
import com.eqdd.yiqidian.http.DialogCallBack;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.HttpResult;
import com.eqdd.yiqidian.http.JsonConverter;
import com.eqdd.yiqidian.utils.DateUtil;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.jakewharton.rxbinding.view.RxView;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.lzy.okrx2.adapter.FlowableBody;

import android.graphics.Color;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.View;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Flowable;

public class SickLeaveListActivity extends BaseActivity {
    private SickLeaveListActivityCustom dataBinding;
    private ArrayList<ClockBean> chosenClockBeans = new ArrayList<>();
    private ArrayList<ClockBean> clockBeans;
    private SlimAdapterEx<ClockBean> slimAdapterEx;
    private TimePickerView time;
    private Date nowDate = new Date();
    private Calendar now;
    private Calendar from;
    private String format;
    private int type;
    SparseArray<String> statusMap = new SparseArray();

    @Override
    public void initBinding() {
        type = getIntent().getIntExtra(Config.TYPE, 0);
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_sick_leave_list);
        String title = "";
        if (type == 0) {
            title = "迟到早退记录";
        } else {
            title = "漏打卡记录";
        }

        initTopTitleBar(View.VISIBLE, title);
        initTopRightText("日期", v -> {
            if (time == null) {
                now = Calendar.getInstance();
                now.setTime(nowDate);
                from = Calendar.getInstance();
                from.setTime(nowDate);
                from.add(Calendar.DATE, -30);
                time = new TimePickerView.Builder(this, (date, v1) -> {
                    updateDate(date);
                })
                        .setOutSideCancelable(true)
                        .setType(new boolean[]{true, true, true, false, false, false})
                        .setDate(now)
                        .setRangDate(from, now)
                        .build();
            }
            time.show();
        });
        statusMap.put(0, "正常");
        statusMap.put(1, "迟到");
        statusMap.put(2, "早退");
        statusMap.put(-1, "可打卡");
        statusMap.put(-2, "漏打卡");
        statusMap.put(-3, "未开始");
    }

    @Override
    public void initData() {
        clockBeans = new ArrayList<>();
        dataBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        slimAdapterEx = SlimAdapterEx.create().register(R.layout.list_item_58, new SlimInjector<ClockBean>() {
            @Override
            public void onInject(ClockBean data, IViewInjector injector) {
                injector.text(R.id.tv_left, data.getStatus() >= 0 ? "打卡时间 " + data.getCreateTime() : "未打卡" + "  规定打卡时间" + data.getClockTime())
                        .text(R.id.tv_right, statusMap.get(data.getStatus()))
                        .checked(R.id.checkbox, data.isChecked())
                        .enable(R.id.checkbox, data.isEnable())
                        .textColor(R.id.tv_right, data.isEnable() ? Color.RED : Color.GRAY);
            }
        }).attachTo(dataBinding.recyclerView).updateData(new ArrayList());
        ItemClickSupport.addTo(dataBinding.recyclerView)
                .setOnItemClickListener((recyclerView, position, v) -> {

                    ClockBean dataItem = slimAdapterEx.getDataItem(position);
                    if (!dataItem.isEnable())
                        return;
                    if (dataItem.isChecked()) {
                        chosenClockBeans.remove(dataItem);
                        dataItem.setChecked(false);
                    } else {
                        chosenClockBeans.add(dataItem);
                        dataItem.setChecked(true);
                    }
                    slimAdapterEx.notifyItemChanged(position);
                });
    }

    @Override
    public void setView() {
        updateDate(new Date());
        RxView.clicks(dataBinding.btSubmit)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(v -> {
                    if (chosenClockBeans.size() == 0) {
                        ToastUtil.showShort("请先选择");
                    } else {
                        Intent intent = new Intent();
                        intent.putParcelableArrayListExtra("list", chosenClockBeans);
                        intent.putExtra("date", format);
                        setResult(Config.SUCCESS, intent);
                        finish();
                    }
                });
    }

    private void updateDate(Date date) {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        format = sf.format(date);
        OkGo.<HttpResult<List<ClockBean>>>post(HttpConfig.BASE_URL + HttpConfig.NOW_CLOCK)
                .params("userGuid", user.getGuid())
                .params("companyId", user.getCompanyId())
                .params("date", format)
                .execute(new DialogCallBack<HttpResult<List<ClockBean>>>(this) {
                    @Override
                    public void onSuccess(Response<HttpResult<List<ClockBean>>> response) {
                        HttpResult<List<ClockBean>> httpResult = response.body();
                        if (httpResult.getStatus() == 200) {
                            clockBeans.clear();
                            nowDate = DateUtil.parseNetTime(response.getRawResponse().header("Date"));
                            Flowable.fromIterable(httpResult.getItems())
                                    .subscribe(clockBean -> {
                                        if (!(clockBean.getStatus() == 1 || clockBean.getStatus() == 2) && type == 0) {
                                            clockBean.setEnable(false);
                                        } else if (!(clockBean.getStatus() == -2) && type == 1) {
                                            clockBean.setEnable(false);
                                        }
                                        clockBeans.add(clockBean);
                                    }, System.out::println, () -> {
                                        chosenClockBeans.clear();
                                        slimAdapterEx.updateData(clockBeans);
                                    });
                        }
                    }
                });
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {

        }
    }
}
